$(function () {
    //定义全局变量
    window.pageNum = 1;
    window.pageSize = 5;
    window.keyword = "";
    //显示数据
    showPage();
});
//关键字查询
$("#searchBtn").click(function () {
    // 在单击响应函数中获取文本框中输入的数据
    var keyword = $.trim($("#keywordInput").val());

    // 验证输入数据是否有效
    if (keyword == null || keyword == "") {
        // 如果无效，提示，停止函数执行
        layer.msg("请输入关键词！");
        return;
    }

    // 如果有效，赋值给window.keyword
    window.keyword = keyword;

    // 调用showPage()重新分页
    showPage();
});

function showPage() {
    $.ajax({
        url: "/yigou/shop/search/by/keyword",
        type: "post",
        dataType: "JSON",
        data: {
            "pageNum": window.pageNum,
            "keyword": window.keyword
        },

        success: function (result) {

            if (result.result == "SUCCESS") {
                //解析数据
                $("#advertisementTableBody").empty();
                // 获取数据集合
                var list = result.data.list;
                // 判断list是否有效
                if (list == null || list.length == 0) {
                    $("#advertisementTableBody")
                        .append("<tr><td colspan='4' style='text-align:center;'>没有查询到数据！</td></tr>");
                    return;
                }
                for (var i = 0; i < list.length; i++) {
                    var advertisement = list[i];

                    //数据
                    var numberTd = "<td>" + (i + 1) + "</td>";
                    var checkBoxTd = "<td><input class='itemBox' advertisementid='" + advertisement.id + "' type='checkbox'></td>";
                    var advertisementSort = "<td>" + advertisement.sort + "</td>";
                    var advertisementIamge = "<td>"+"<img src='"+advertisement.iamge+"'>"+"</td>";
                    var advertisementName = "<td>" + advertisement.name + "</td>";
                    var advertisementUid = "<td>" + advertisement.uid + "</td>";
                    var advertisementDisplay = "<td>" + advertisement.display + "</td>";
                    var advertisementModify = "<td>" + advertisement.modify + "</td>";
                    //按钮
                    var pencilBtn = "<button advertisementId='" + advertisement.id + "' type='button' class='btn btn-primary btn-xs editBtn'>审核</button>";
                    var removeBtn = "<button advertisementId='" + advertisement.id + "' type='button' class='btn btn-danger btn-xs removeBtn'>下架</button>";

                    var btnTd = "<td>" + pencilBtn + " " + removeBtn + "</td>";
                    var tr = "<tr>" + numberTd + checkBoxTd + advertisementSort + advertisementIamge + advertisementName + advertisementUid + advertisementDisplay + advertisementModify + btnTd + "</tr>";


                    // 将前面拼好的HTML代码追加到#roleTableBody中
                    $("#advertisementTableBody").append(tr);
                }

                //显示分页导航
                initPagination(result.data);
            } else {
                layer.msg(result.message);
            }
        }
    });
}

//声明函数封装导航条初始化操作
function initPagination(pageInfo) {
    // 声明变量存储分页导航条显示时的属性设置
    var paginationProperties = {
        num_edge_entries: 3,        //边缘页数
        num_display_entries: 5,      //主体页数
        callback: pageselectCallback, //回调函数
        items_per_page: window.pageSize,  //每页显示数据数量，就是pageSize
        current_page: window.pageNum - 1,//当前页页码
        prev_text: "上一页",       //上一页文本
        next_text: "下一页"        //下一页文本
    };

    // 显示分页导航条
    $("#Pagination").pagination(pageInfo.total, paginationProperties);
}

// 在每一次点击“上一页”、“下一页”、“页码”时执行这个函数跳转页面
function pageselectCallback(pageIndex, jq) {
    // pageIndex从0开始，pageNum从1开始
    var pageNum = pageIndex + 1;
    // 跳转页面
    window.pageNum = pageNum;
    var keyword = window.keyword;
    showPage();
    return false;
}

// 全选/全不选功能
$("#summaryBox").click(function () {
    // 1.获取当前checkbox的选中状态
    var currentStatus = this.checked;
    // 2.设置itemBox的选中状态
    $(".itemBox").prop("checked", currentStatus);

});

$(function () {

    $("#summaryBox").click(function () {
        //设置itemBox的选中状态
        $(".itemBox").prop("checked", this.checked);
    });

    $("#batchRemoveBtn").click(function () {
        //获取被选中的itemBox数组长度
        var length = $(".itemBox:checked").length;
        //如果长度为0,说明没没有选择itemBox
        if (length == 0) {
            layer.msg("请至少选择一条");
            return;
        }
        //在全局作用域内创建roleIdArray
        window.roleIdArray = new Array();
        //遍历
        $(".itemBox:checked").each(function () {
            //通过CheckBox的roleid属性获取roleid值
            var roleId = $(this).attr("advertisementid");
            window.roleIdArray.push(roleId);
        });
        //调用函数打开模态框
        showRemoveConfirmModal();
    });
    //绑定单击响应函数
    $("#addBtn").click(function () {
        $("#addModal").modal("show");
    });
});

//删除
function showRemoveConfirmModal() {
    // 1.将模态框显示出来
    $("#confirmModal").modal("show");

    //显示要删除的数据
    var requestBody = JSON.stringify(window.roleIdArray);
    console.log(requestBody)
    // 2.发送Ajax请求
    $.ajax({
        url: "/user/get/list/by/id/list",
        type: "post",
        data: requestBody,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        success: function (ajaxResult) {
            if (ajaxResult.result == "SUCCESS") {
                // 5.如果成功，显示数据
                // 3.清空#confirmModalTableBody
                $("#confirmModalTableBody").empty();
                // 4.填充#confirmModalTableBody
                var certList = ajaxResult.data;
                for (var i = 0; i < certList.length; i++) {

                    // 5.获取角色相关数据
                    var cert = certList[i];

                    var id = cert.id;
                    var username = cert.username;
                    var loginname = cert.loginname;
                    var roleid = cert.roleid;
                    var trHTML = "<tr><td>" + id + "</td><td>" + username + "</td><td>" + loginname + "</td><td>" + roleid + "</td></tr>";

                    // 6.执行填充
                    $("#confirmModalTableBody").append(trHTML);
                }
            } else {
                layer.msg(ajaxResult.message);
                return null;
            }
        }
    });
}

//确认删除
$("#confirmModalBtn").click(function () {
    var requestBody = JSON.stringify(window.roleIdArray);
    $.ajax({
        url: "/user/batch/remove",
        type: "post",
        data: requestBody,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        success: function (response) {
            var result = response.result;
            if (result == "SUCCESS") {
                layer.msg("删除成功！");
                // 如果删除成功，则重新调用分页方法
                showPage();
            }
            if (result == "FAILED") {
                layer.msg(response.message);
            }
            // 不管成功还是失败，都需要关掉模态框
            $("#confirmModal").modal("hide");

        },
        "error": function (response) {
            layer.msg(response.message);
        }
    });
});

//单条删除  advertisementTableBody嗯这个是从
$("#advertisementTableBody").on("click", ".removeBtn", function () {
    //获取当前记录roleId
    var roleId = $(this).attr("advertisementId");
    //存入全局变量数组
    window.roleIdArray = new Array();
    window.roleIdArray.push(roleId);
    //打开模态框
    showRemoveConfirmModal();
});

//修改
$("#advertisementTableBody").on("click", ".editBtn", function () {

    //获取当前按钮的roleId
    window.roleId = $(this).attr("advertisementId");

    //获取当前按钮所在行的roleName
    var adminusername = $(this).parents("tr").children("td:eq(2)").text();
    var adminloginname = $(this).parents("tr").children("td:eq(3)").text();
    var roleId = $(this).parents("tr").children("td:eq(4)").text();

    //修改模态框中文本框的value值，目的是在显示roleName
    $("#userNameInputEdit").val(adminusername);
    $("#loginNameInputEdit").val(adminloginname);
    $("#roleIdInputEdit").val(roleId);

    //打开模态框
    $("#editModal").modal("show");
});

//确认修改
$("#editModalBtn").click(function () {
    // 1.获取文本框值
    var username = $.trim($("#userNameInputEdit").val());
    if (username == null || username == "") {
        layer.msg("请输入有效登录名称！");
        return;
    }
    var loginname = $.trim($("#loginNameInputEdit").val());
    if (loginname == null || loginname == "") {
        layer.msg("请输入有效的用户名称");
        return;
    }
    var roleid = $.trim($("#roleIdInputEdit").val());
    if (roleid == null || roleid == "") {
        layer.msg("请输入有效的角色编号");
        return;
    }
    $.ajax({
        url: "/user/update/user",
        type: "post",
        data: {
            "id": window.roleId,//这个id我取的对吗
            "username": username,
            "loginname": loginname,
            "roleid": roleid
        },
        dataType: "json",
        success: function (response) {
            var result = response.result;
            if (result == "SUCCESS") {
                layer.msg("操作成功！");
                // 3.操作成功重新分页
                showPage();
            }
            if (result == "FAILED") {
                layer.msg(response.message);
            }

            // 4.不管成功还是失败，关闭模态框
            $("#editModal").modal("hide");
        }
    });
});